//
//  BankCardViewController.m
//  HaierGMS_APP
//
//  Created by 堂堂 on 16/12/1.
//  Copyright © 2016年 堂堂. All rights reserved.
//

#import "BankCardViewController.h"
#import "BankCardTableViewCell.h"
#import "UIColor+Hex.h"
#import "AFHTTPRequestOperationManager.h"
#import "MBProgressHUD+MJ.h"
#import "HttpReauestParam.h"
#import "UserDefaultUtil.h"
#import "AddBankCardViewController.h"
#import "WalletCashViewController.h"
@interface BankCardViewController ()

@property NSArray *data;

@end

@implementation BankCardViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    UINib *nib = [UINib nibWithNibName:@"BankCardTableViewCell" bundle:nil];
    
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.tableView registerNib:nib forCellReuseIdentifier:@"bank_cell"];
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    //self.tableView.tableFooterView = [[UIView alloc] init];
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _data.count;
}

// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSDictionary *dic = _data[indexPath.row];
    
    BankCardTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"bank_cell"];
    
    cell.bank_image = [cell viewWithTag:11];
    cell.lab_bank = [cell viewWithTag:111];
    cell.lab_num = [cell viewWithTag:1111];
    cell.bg_view = [cell viewWithTag:11111];
    
    [cell.bank_image setImage:[UIImage imageNamed:@"default_image"]];
    [cell.bank_image loadImage:[NSURL URLWithString:dic[@"bankImage"]]];
    
    cell.lab_bank.text = dic[@"bankName"];
    cell.lab_num.text = [NSString stringWithFormat:@"%@",dic[@"bankCard"]];
    cell.bg_view.backgroundColor = [UIColor colorWithHexString:dic[@"bankColor"]];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (_isCash) {
        WalletCashViewController *vc = self.navigationController.viewControllers[self.navigationController.viewControllers.count - 2];
        vc.chooseBank = _data[indexPath.row];
        [self.navigationController popToViewController:vc animated:YES];
    }
    
    [tableView deselectRowAtIndexPath:indexPath animated:NO];

    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 128;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)add_content:(id)sender {
    
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"App_Main" bundle:[NSBundle mainBundle]];
    AddBankCardViewController *addBank = [sb instantiateViewControllerWithIdentifier:@"add_bank_view"];
    [self.navigationController pushViewController:addBank animated:YES];
}
- (IBAction)back_click:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)viewWillAppear:(BOOL)animated{
    [self getData];
}
-(void) getData{
    
    NSString *userId =[UserDefaultUtil getUserId];
    NSDictionary * dic = @{@"identifier": userId };
    
    NSLog(@"%@",dic);
    
    HttpReauestParam * param = [[HttpReauestParam alloc]initWithData:@"person_binding_bank_card_info_get" content:[self dictionaryToJson:dic] urlType:0];
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
    // [MBProgressHUD showMessage:@"获取订单"];
    [manage POST:param.SEVICE_URL parameters:param.param success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSDictionary * data = [NSJSONSerialization JSONObjectWithData:operation.responseObject options:0 error:nil];
        
        [MBProgressHUD hideHUD];
        if ([data[@"success"] boolValue]) {
            
            
             _data = data[@"result"];
            [self.tableView reloadData];
            
        }else{
            [MBProgressHUD showError:data[@"errorMsg"]];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [MBProgressHUD hideHUD];
        [MBProgressHUD showError:@"网络连接失败"];
    }];
}


-(NSString*)dictionaryToJson:(NSDictionary *)dic

{
    
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}

-(void)tableView:(UITableView*)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath*)indexPath

{
    
    //如果是删除
    
    if(editingStyle==UITableViewCellEditingStyleDelete)
        
    {
        
        [self removeData:[NSString stringWithFormat:@"%i",_data[indexPath.row][@"id"]]];
       
    }
    
}
-(NSString*)tableView:(UITableView*)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath*)indexPath

{
    
    return@"删除";
    
}

//是否允许编辑行，默认是YES

-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath

{
    
    return YES;
    
}

-(void) removeData:(NSString *) bankid{
    
    NSString *userId =[UserDefaultUtil getUserId];
    NSDictionary * dic = @{@"identifier": userId ,@"id":bankid,@"flag":@"1",@"cardNum":@"",@"carUserName":@"",@"phone":@""};
    
    NSLog(@"%@",dic);
    
    HttpReauestParam * param = [[HttpReauestParam alloc]initWithData:@"bank_card_operator" content:[self dictionaryToJson:dic] urlType:0];
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
     [MBProgressHUD showMessage:@"删除"];
    [manage POST:param.SEVICE_URL parameters:param.param success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSDictionary * data = [NSJSONSerialization JSONObjectWithData:operation.responseObject options:0 error:nil];
        
        [MBProgressHUD hideHUD];
        if ([data[@"success"] boolValue]) {
            
            
            [self getData];
        }else{
            [MBProgressHUD showError:data[@"errorMsg"]];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [MBProgressHUD hideHUD];
        [MBProgressHUD showError:@"网络连接失败"];
    }];
}

@end
